/**
 *
 */
package cn.dw.mm.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.dw.mm.domain.User;
import cn.dw.mm.service.UserService;

/**
 * @author aubrey
 * @date  下午2:40:24
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/page")
	public String page() {
		return "user/list";
	}
	
	
	@RequestMapping("/add")
	@ResponseBody
	public String add(User user) {
		userService.insertSelective(user);
		return "{\"status\":\"成功\"}";
	}
	
	@RequestMapping("/query")
	@ResponseBody
	public List<User> query(User user) {
		return  userService.selectAll(user);
//		return "{\"status\":\"成功\"}";
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public String del(String ids) {
		String[] strIds = ids.split(",");
		for(String i : strIds) {
			userService.deleteByPrimaryKey(Integer.parseInt(i));
		}
		return "{\"status\":\"成功\"}";
	}
	
	
	@RequestMapping("/excel")
	public void excel(User user,HttpServletRequest request,HttpServletResponse response) {
		HSSFWorkbook wb = userService.excel(user);
		
		response.setContentType("text/html;charset=utf-8");
		OutputStream out = null;
		try {
			request.setCharacterEncoding("UTF-8");
			out = response.getOutputStream();
			wb.write(out);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		response.setContentType("application/x-msdownload;");
		response.setHeader("Content-disposition", "attachment; filename=user.xlsx");
//		response.setHeader("Content-Length", String.valueOf(fileLength));
		try {
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	

}
